<template>
  <div class="exhibition-detail-container">
    <el-card v-loading="loading">
      <!-- 返回按钮 -->
      <div class="back-link">
        <el-button icon="el-icon-arrow-left" type="text" @click="goBack">返回展览列表</el-button>
      </div>
      
      <!-- 展览信息 -->
      <div v-if="exhibition.id" class="exhibition-info">
        <div class="exhibition-header">
          <div class="exhibition-title">
            <h2>{{ exhibition.name }}</h2>
            <el-tag :type="getStatusType(exhibition.status)">{{ getStatusText(exhibition.status) }}</el-tag>
          </div>
          <el-button 
            type="primary" 
            @click="makeReservation" 
            :disabled="exhibition.status !== 'IN_PROGRESS'"
          >预约参观</el-button>
        </div>
        
        <el-divider></el-divider>
        
        <div class="exhibition-content">
          <div class="exhibition-image">
            <img style="width: 200px; height: 200px;" :src="exhibition.image || defaultImage" alt="展览图片">
          </div>
          
          <div class="exhibition-details">
            <div class="detail-item">
              <span class="label">展览地点：</span>
              <span>{{ exhibition.location }}</span>
            </div>
            <div class="detail-item">
              <span class="label">展览时间：</span>
              <span>{{ formatDateRange(exhibition.startTime, exhibition.endTime) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">开放时间：</span>
              <span>{{ exhibition.dailyOpenTime }} - {{ exhibition.dailyCloseTime }}</span>
            </div>
            <div class="detail-item">
              <span class="label">每日限额：</span>
              <span>{{ exhibition.dailyLimit }}人</span>
            </div>
            <div class="detail-item description">
              <span class="label">展览简介：</span>
              <div class="description-content">{{ exhibition.description }}</div>
            </div>
          </div>
        </div>
        
        <!-- 藏品列表 -->
        <div class="collection-section">
          <h3>展览藏品</h3>
          <el-divider></el-divider>
          
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in collections" :key="item.id" class="collection-item">
              <el-card :body-style="{ padding: '0px' }" shadow="hover">
                <div class="collection-img">
                  <img  style="width: 200px; height: 200px;" :src="item.image || defaultCollectionImage" alt="藏品图片">
                </div>
                <div class="collection-info">
                  <h4>{{ item.name }}</h4>
                  <p class="collection-era">{{ item.era }}</p>
                  <p class="collection-type">{{ item.type }}</p>
                  <el-button type="text" @click="showCollectionDetail(item)">查看详情</el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <!-- 空数据提示 -->
          <el-empty v-if="collections.length === 0" description="暂无藏品信息"></el-empty>
        </div>
      </div>
      
      <!-- 数据为空时显示 -->
      <el-empty v-else-if="!loading" description="未找到展览信息"></el-empty>
    </el-card>
    
    <!-- 预约对话框 -->
    <el-dialog title="展览预约" :visible.sync="dialogVisible" width="500px">
      <el-form :model="reservationForm" :rules="reservationRules" ref="reservationFormRef" label-width="100px">
        <el-form-item label="展览名称">
          <el-input v-model="exhibition.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="展览地点">
          <el-input v-model="exhibition.location" disabled></el-input>
        </el-form-item>
        <el-form-item label="预约日期" prop="reservationDate">
          <el-date-picker
            v-model="reservationForm.reservationDate"
            type="date"
            placeholder="选择预约日期"
            :picker-options="datePickerOptions"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间段" prop="timeSlot">
          <el-select v-model="reservationForm.timeSlot" placeholder="请选择预约时间段" style="width: 100%">
            <el-option
              v-for="item in timeSlots"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约人数" prop="visitorCount">
          <el-input-number v-model="reservationForm.visitorCount" :min="1" :max="10" style="width: 100%"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReservation" :loading="submitLoading">提交预约</el-button>
      </div>
    </el-dialog>
    
    <!-- 藏品详情对话框 -->
    <el-dialog title="藏品详情" :visible.sync="collectionDialogVisible" width="600px">
      <div v-if="currentCollection.id" class="collection-detail">
        <div class="collection-detail-image">
          <img  style="width: 200px; height: 200px;" :src="currentCollection.image || defaultCollectionImage" alt="藏品图片">
        </div>
        <div class="collection-detail-info">
          <h3>{{ currentCollection.name }}</h3>
          <div class="detail-item">
            <span class="label">年代：</span>
            <span>{{ currentCollection.era }}</span>
          </div>
          <div class="detail-item">
            <span class="label">类型：</span>
            <span>{{ currentCollection.type }}</span>
          </div>
          <div class="detail-item description">
            <span class="label">描述：</span>
            <div class="description-content">{{ currentCollection.description }}</div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  name: 'ExhibitionDetail',
  data() {
    return {
      // 展览ID
      exhibitionId: null,
      // 展览详情
      exhibition: {},
      // 藏品列表
      collections: [],
      // 加载状态
      loading: false,
      // 默认展览图片
      defaultImage: 'https://via.placeholder.com/600x400?text=文化馆展览',
      // 默认藏品图片
      defaultCollectionImage: 'https://via.placeholder.com/300x300?text=文化馆藏品',
      // 预约对话框
      dialogVisible: false,
      // 预约表单
      reservationForm: {
        reservationDate: '',
        timeSlot: '',
        visitorCount: 1
      },
      // 预约表单验证规则
      reservationRules: {
        reservationDate: [
          { required: true, message: '请选择预约日期', trigger: 'change' }
        ],
        timeSlot: [
          { required: true, message: '请选择预约时间段', trigger: 'change' }
        ],
        visitorCount: [
          { required: true, message: '请输入预约人数', trigger: 'blur' }
        ]
      },
      // 日期选择器配置
      datePickerOptions: {
        disabledDate(time) {
          // 禁用今天之前的日期
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      // 时间段选项
      timeSlots: [
        { value: '09:00-11:00', label: '上午 09:00-11:00' },
        { value: '13:00-15:00', label: '下午 13:00-15:00' },
        { value: '15:00-17:00', label: '下午 15:00-17:00' }
      ],
      // 提交预约加载状态
      submitLoading: false,
      // 藏品详情对话框
      collectionDialogVisible: false,
      // 当前选中的藏品
      currentCollection: {}
    }
  },
  created() {
    // 获取路由参数中的展览ID
    this.exhibitionId = this.$route.params.id
    if (this.exhibitionId) {
      // 获取展览详情
      this.getExhibitionDetail()
      // 获取展览藏品列表
      this.getExhibitionCollections()
    }
  },
  methods: {
    // 获取展览详情
    async getExhibitionDetail() {
      this.loading = true
      try {
        const { data: res } = await this.$http.get(`/exhibition/${this.exhibitionId}`)
        if (res.code === 200) {
          this.exhibition = res.data || {}
        } else {
          this.$message.error(res.message || '获取展览详情失败')
        }
      } catch (error) {
        console.error('获取展览详情失败', error)
        this.$message.error('获取展览详情失败，请稍后重试')
        // 使用模拟数据
        this.exhibition = this.getMockExhibition()
      } finally {
        this.loading = false
      }
    },
    // 获取展览藏品列表
    async getExhibitionCollections() {
      try {
        const { data: res } = await this.$http.get(`collection/exhibition/${this.exhibitionId}`)
        if (res.code === 200) {
          this.collections = res.data || []
        } else {
          this.$message.error(res.message || '获取藏品列表失败')
        }
      } catch (error) {
        console.error('获取藏品列表失败', error)
        // 使用模拟数据
        this.collections = this.getMockCollections()
      }
    },
    // 返回展览列表
    goBack() {
      this.$router.push('/exhibition/list')
    },
    // 格式化日期范围
    formatDateRange(startTime, endTime) {
      if (!startTime || !endTime) return ''
      return `${moment(startTime).format('YYYY-MM-DD')} 至 ${moment(endTime).format('YYYY-MM-DD')}`
    },
    // 获取展览状态文本
    getStatusText(status) {
      const statusMap = {
        'NOT_STARTED': '未开始',
        'IN_PROGRESS': '进行中',
        'ENDED': '已结束'
      }
      return statusMap[status] || '未知'
    },
    // 获取展览状态类型
    getStatusType(status) {
      const typeMap = {
        'NOT_STARTED': 'info',
        'IN_PROGRESS': 'success',
        'ENDED': 'danger'
      }
      return typeMap[status] || ''
    },
    // 打开预约对话框
    makeReservation() {
      if (this.exhibition.status !== 'ONGOING') {
        return this.$message.warning('只能预约进行中的展览')
      }
      this.dialogVisible = true
      // 重置表单
      this.reservationForm = {
        reservationDate: '',
        timeSlot: '',
        visitorCount: 1
      }
      // 如果表单引用存在，重置验证
      if (this.$refs.reservationFormRef) {
        this.$refs.reservationFormRef.resetFields()
      }
    },
    // 提交预约
    submitReservation() {
      this.$refs.reservationFormRef.validate(async valid => {
        if (!valid) return
        this.submitLoading = true
        try {
          // 构建预约数据
          const reservationData = {
            userId: this.$store.state.userInfo.id,
            exhibitionId: this.exhibitionId,
            reservationDate: moment(this.reservationForm.reservationDate).format('YYYY-MM-DD'),
            timeSlot: this.reservationForm.timeSlot,
            visitorCount: this.reservationForm.visitorCount
          }
          // 发送预约请求
          const { data: res } = await this.$http.post('/exhibition-reservation', reservationData)
          if (res.code === 200) {
            this.$message.success('预约成功，请在"我的预约"中查看预约详情')
            this.dialogVisible = false
          } else {
            this.$message.error(res.message || '预约失败')
          }
        } catch (error) {
          console.error('预约失败', error)
          this.$message.error('预约失败，请稍后重试')
        } finally {
          this.submitLoading = false
        }
      })
    },
    // 显示藏品详情
    showCollectionDetail(collection) {
      this.currentCollection = collection
      this.collectionDialogVisible = true
    },
    // 获取模拟展览数据
    getMockExhibition() {
      return {
        id: this.exhibitionId,
        name: '古代陶瓷艺术展',
        description: '本展览展示了中国古代陶瓷艺术的发展历程，从原始彩陶到唐三彩，从宋代青瓷到明清青花瓷，全面展现了中国陶瓷艺术的辉煌成就和独特魅力。通过精选的展品，观众可以了解不同时期陶瓷的工艺特点、审美变化和文化内涵。',
        location: '文化馆一楼展厅',
        startTime: '2023-01-01',
        endTime: '2023-12-31',
        dailyOpenTime: '09:00',
        dailyCloseTime: '17:00',
        dailyLimit: 200,
        status: 'ONGOING',
        image: ''
      }
    },
    // 获取模拟藏品数据
    getMockCollections() {
      return [
        {
          id: '1',
          name: '唐三彩马',
          era: '唐代',
          type: '陶瓷',
          description: '唐三彩是盛行于唐代的一种低温釉陶器，以黄、绿、白三种釉彩为主。这件唐三彩马造型生动，体现了唐代陶瓷工艺的高超水平。',
          image: ''
        },
        {
          id: '2',
          name: '青花缠枝莲纹碗',
          era: '明代',
          type: '瓷器',
          description: '明代青花瓷器，碗内外绘缠枝莲纹，笔法流畅，青花发色纯正，是明代景德镇瓷器的代表作品。',
          image: ''
        },
        {
          id: '3',
          name: '汝窑天青釉盘',
          era: '宋代',
          type: '瓷器',
          description: '汝窑是宋代五大名窑之一，以天青釉色著称。此盘釉色莹润，开片自然，展现了宋代审美的含蓄与典雅。',
          image: ''
        }
      ]
    }
  }
}
</script>

<style lang="scss" scoped>
.exhibition-detail-container {
  .back-link {
    margin-bottom: 20px;
  }
  
  .exhibition-info {
    .exhibition-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .exhibition-title {
        display: flex;
        align-items: center;
        
        h2 {
          margin: 0 15px 0 0;
        }
      }
    }
    
    .exhibition-content {
      display: flex;
      margin: 20px 0;
      
      @media (max-width: 768px) {
        flex-direction: column;
      }
      
      .exhibition-image {
        width: 40%;
        margin-right: 20px;
        
        @media (max-width: 768px) {
          width: 100%;
          margin-right: 0;
          margin-bottom: 20px;
        }
        
        img {
          width: 100%;
          border-radius: 4px;
        }
      }
      
      .exhibition-details {
        flex: 1;
        
        .detail-item {
          margin-bottom: 15px;
          line-height: 1.5;
          
          .label {
            font-weight: bold;
            color: #303133;
          }
          
          &.description {
            .description-content {
              margin-top: 5px;
              line-height: 1.8;
              text-align: justify;
            }
          }
        }
      }
    }
  }
  
  .collection-section {
    margin-top: 30px;
    
    h3 {
      font-size: 18px;
      font-weight: bold;
      color: #303133;
    }
    
    .collection-item {
      margin-bottom: 20px;
      
      .collection-img {
        height: 180px;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .collection-info {
        padding: 14px;
        
        h4 {
          margin: 0 0 10px;
          font-size: 16px;
        }
        
        .collection-era, .collection-type {
          margin: 5px 0;
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }
  
  .collection-detail {
    display: flex;
    
    @media (max-width: 768px) {
      flex-direction: column;
    }
    
    .collection-detail-image {
      width: 40%;
      margin-right: 20px;
      
      @media (max-width: 768px) {
        width: 100%;
        margin-right: 0;
        margin-bottom: 20px;
      }
      
      img {
        width: 100%;
        border-radius: 4px;
      }
    }
    
    .collection-detail-info {
      flex: 1;
      
      h3 {
        margin-top: 0;
        margin-bottom: 15px;
      }
      
      .detail-item {
        margin-bottom: 15px;
        line-height: 1.5;
        
        .label {
          font-weight: bold;
          color: #303133;
        }
        
        &.description {
          .description-content {
            margin-top: 5px;
            line-height: 1.8;
            text-align: justify;
          }
        }
      }
    }
  }
}